package view;

import javax.swing.*;
import javax.swing.table.TableCellEditor;
import javax.swing.table.TableCellRenderer;
import java.awt.*;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;

public class ButtonEditor extends AbstractCellEditor implements TableCellEditor {
    private JButton button;
    private String editButtonText;
    private String deleteButtonText;
    private ActionListener actionListener;
    private String currentValue;
    
    public ButtonEditor(ActionListener listener) {
        this(listener, "编辑", "删除");
    }
    
    public ButtonEditor(ActionListener listener, String editText) {
        this(listener, editText, "删除");
    }
    
    public ButtonEditor(ActionListener listener, String editText, String deleteText) {
        this.actionListener = listener;
        this.editButtonText = editText;
        this.deleteButtonText = deleteText;
        
        button = new JButton();
        button.setOpaque(true);
        button.addActionListener(e -> {
            if (currentValue != null) {
                actionListener.actionPerformed(new ActionEvent(
                    button, 
                    ActionEvent.ACTION_PERFORMED, 
                    currentValue
                ));
            }
            fireEditingStopped();
        });
    }
    
    public TableCellRenderer getRenderer() {
        return new ButtonRenderer(editButtonText, deleteButtonText);
    }
    
    @Override
    public Component getTableCellEditorComponent(JTable table, Object value,
            boolean isSelected, int row, int column) {
        currentValue = value != null ? value.toString() : null;
        if (currentValue != null) {
            button.setText(currentValue);
        }
        return button;
    }
    
    @Override
    public Object getCellEditorValue() {
        return currentValue;
    }
    
    private static class ButtonRenderer extends JButton implements TableCellRenderer {
        private String editText;
        private String deleteText;
        
        public ButtonRenderer(String editText, String deleteText) {
            this.editText = editText;
            this.deleteText = deleteText;
            setOpaque(true);
        }
        
        @Override
        public Component getTableCellRendererComponent(JTable table, Object value,
                boolean isSelected, boolean hasFocus, int row, int column) {
            if (value != null) {
                setText(value.toString());
            }
            return this;
        }
    }
} 